package com.md.api.service.impl;

import cn.hutool.core.date.DateUtil;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.md.api.common.exception.BusinessException;
import com.md.api.common.utils.*;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.constants.SysConstants;
import com.md.api.entity.dto.ComposeCommitDto;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.enums.*;
import com.md.api.entity.util.Page;
import com.md.api.service.MotService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author liujie
 * @ClassName ShoppingCartServiceImpl
 **/

@Slf4j
@Service
public class MotServiceImpl implements MotService {

    @Value("${wx.pay.motNotifyUrl}")
    private String motNotifyUrl;
    @Value("${wx.pay.backMotNotifyUrl}")
    private String backMotNotifyUrl;
    @Resource
    TokenUtil tokenUtil;
    @Resource
    UserCouponRecordMapper couponRecordMapper;
    @Resource
    UserBalanceRecordMapper balanceRecordMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    UserMessageMapper userMessageMapper;
    @Resource
    WxPayService wxService;
    @Resource
    MotOrderMapper motOrderMapper;
    @Resource
    MotReservationMapper reservationMapper;
    @Resource
    SiteInfoMapper siteInfoMapper;
    @Resource
    UserCarMapper userCarMapper;
    @Resource
    SiteServiceContentMapper serviceContentMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    SiteServicePredetermineRecordMapper predetermineRecordMapper;
    @Resource
    SiteServicePredetermineDetailMapper predetermineDetailMapper;

    @Override
    public HttpResult dayHasRoom() {
        List<DayHasMot> list = predetermineRecordMapper.dayHasMot();
        return new HttpResult(list);
    }

    @Override
    public HttpResult predetermineDetail(ComposeQueryDto qto) {
        Integer isToday = 0;
        if (DateUtils.formatD(qto.getPredetermineDate()).equals(DateUtils.formatD(new Date()))){
            isToday = 1;
        }
        List<SiteServicePredetermineRecord> records = predetermineRecordMapper.getByServiceIdAndDate(qto.getServiceId(), qto.getPredetermineDate(),isToday);
        return new HttpResult(records);
    }


    @Override
    public HttpResult myMotOrder(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(MotOrder.class);
        String userId = tokenUtil.getUserId(request);
        List<MotOrder> list = motOrderMapper.list(userId,null,null,qto.getMotType(),qto.getStatus(),null,null,null);
        for (MotOrder order:list){
            order.setCar(userCarMapper.getByCarId(order.getCarId()));
        }
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult orderDetail(HttpServletRequest request, MotOrder order) {
        MotOrder dborder = motOrderMapper.getByMotNo(order.getMotNo());
        dborder.setCar(userCarMapper.getByCarId(dborder.getCarId()));
        dborder.setServiceContent(serviceContentMapper.getByServiceId(dborder.getServiceId()));
        dborder.setSiteInfo(siteInfoMapper.getBySiteId(dborder.getSiteId()));
        return new HttpResult(dborder);
    }

    @Override
    public HttpResult myReservation(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(MotReservation.class);
        String userId = tokenUtil.getUserId(request);
        List<MotReservation> list = reservationMapper.list(userId, null,qto.getStatus());
        for (MotReservation order:list){
            order.setCar(userCarMapper.getByCarId(order.getCarId()));
            order.setSiteInfo(siteInfoMapper.getBySiteId(order.getSiteId()));
        }
        page.setResult(list);
        return new HttpResult(page);
    }



    @Override
    public HttpResult motTrade(HttpServletRequest request, ComposeCommitDto qto) {
        Map resultMap = new HashMap();
        SiteInfo siteInfo = siteInfoMapper.getBySiteId(qto.getSiteId());
        UserCar car = userCarMapper.getByCarId(qto.getCarId());
//        if (!siteInfo.getMotCarType().contains(car.getCarType())){
//            return HttpResult.fail("该站点暂不支持检测"+car.getCarType()+"！");
//        }
//        if (StringUtils.isNotEmpty(car.getEnergySign())
//                &&!car.getEnergySign().equals("汽油")&&siteInfo.getIsEnergy()==-1){
//            return HttpResult.fail("该站点暂不支持检测新能源车");
//        }

        SiteServicePredetermineRecord dbPredetermine = predetermineRecordMapper.getByPredetermineId(qto.getPredetermineId());
        if (dbPredetermine.getPredetermineCount()>=dbPredetermine.getTotalCount()) {
            return HttpResult.fail("该包房此时间段已预约完！");
        }
//        //防止重复预定
//        SiteServicePredetermineDetail dbPredetermineDetail =  predetermineDetailMapper.hasPredetermined(car.getUserId(),qto.getServiceId(),dbPredetermine.getPredetermineDate());
//        if (null!=dbPredetermineDetail){
//            return HttpResult.fail("当天已有预定，请确认！");
//        }



        SiteServiceContent serviceContent = serviceContentMapper.getByServiceId(qto.getServiceId());
        //上门接车费
        BigDecimal pickUpFee = new BigDecimal("0");
        if (null!=qto.getMotType()&&qto.getMotType()==2){
            double distance = DistanceUtils.haversineDistance(siteInfo.getLatitude(), siteInfo.getLongitude(), qto.getLatitude(), qto.getLongitude());
            if (distance>10000){
                return HttpResult.fail("已超过接车距离,请选择最近站点！");
            }
            //获取接车费
            SysConfig sysConfig = sysConfigMapper.getByKey(SysConstants.PICK_UP_FEE);
            pickUpFee = pickUpFee.add(new BigDecimal(sysConfig.getConfigValue()));
            resultMap.put("pickUpFee",NumberUtils.numFormat(pickUpFee));
        }

        Double money = serviceContent.getFuelMoney();
//        if (StringUtils.isNotEmpty(car.getEnergySign())
//                &&!car.getEnergySign().equals("汽油")){
//            money = serviceContent.getEnergyMoney();
//        }


        BigDecimal totalMoney = new BigDecimal(money);
        BigDecimal totalPay = new BigDecimal(money);
        //使用优惠券特别折扣
        if (StringUtils.isNotEmpty(qto.getCouponRecordId())){
            //校验折扣券是否可用，防止爬虫通过过期券调用
            UserCouponRecord couponRecord = couponRecordMapper.getByCouponRecordId(qto.getCouponRecordId());
            if (couponRecord.getStatus()!=0){
                return HttpResult.fail("该券已经使用或已失效！");
            }
            if (couponRecord.getUseWay()==2){
                return HttpResult.fail("该券不是车检优惠券！");
            }
            Integer couponWay = couponRecord.getCouponWay();
            BigDecimal discount = new BigDecimal(new Double(couponRecord.getDiscount()).toString());
            if (couponWay==1){//折扣券
                totalPay = totalMoney.multiply(discount);
                Double discountMoney = totalMoney.subtract(totalPay).doubleValue();
                resultMap.put("discountMoney",NumberUtils.numFormat(discountMoney));
            }else if (couponWay==2){//现金券
                totalPay = totalMoney.subtract(discount);
                resultMap.put("discountMoney",NumberUtils.numFormat(discount));
            }else{//满减券
                //最低金额是否达到
                if(totalMoney.doubleValue()<couponRecord.getLowerMoney()){
                    return HttpResult.fail("未达到满减券最低消费金额！");
                }
                totalPay = totalMoney.subtract(discount);
                resultMap.put("discountMoney",NumberUtils.numFormat(discount));
            }
        }
        //佣金
        if (null!=qto.getCommission()) {
            UserInfo user = userMapper.getByUserId(car.getUserId());
            if (null==user.getBalance()||user.getBalance()< qto.getCommission()){
                return HttpResult.fail("佣金余额不足！！");
            }
            totalPay = BigDecimalUtil.sub(totalPay.doubleValue(), qto.getCommission());
            resultMap.put("commission",NumberUtils.numFormat( qto.getCommission()));
        }
        //接车费
        if (null!=qto.getMotType()&&qto.getMotType()==2){
            totalPay = totalPay.add(pickUpFee);
        }
        resultMap.put("totalPay",NumberUtils.numFormat(totalPay.doubleValue()));
        resultMap.put("totalMoney",NumberUtils.numFormat(totalMoney.doubleValue()));
        return new HttpResult(resultMap);
    }


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @Override
    public HttpResult order(HttpServletRequest request, ComposeCommitDto qto) throws WxPayException {

        String userId = tokenUtil.getUserId(request);
        UserInfo user = userMapper.getByUserId(userId);
        HttpResult httpResult = this.motTrade(request, qto);
        Map resultMap = (Map)httpResult.getData();
        Double totalMoney = null!=resultMap.get("totalMoney")?Double.valueOf(resultMap.get("totalMoney").toString()):null;
        Double totalPay = null!=resultMap.get("totalPay")?Double.valueOf(resultMap.get("totalPay").toString()):null;
        Double pickUpFee = null!=resultMap.get("pickUpFee")?Double.valueOf(resultMap.get("pickUpFee").toString()):null;
        Double discountMoney = null!=resultMap.get("discountMoney")?Double.valueOf(resultMap.get("discountMoney").toString()):null;
        if (totalPay<0){
            return HttpResult.fail("金额获取失败，请确认！");
        }
        //创建预约记录
        SiteServicePredetermineRecord dbPredetermine = predetermineRecordMapper.getByPredetermineId(qto.getPredetermineId());
        SiteServicePredetermineDetail detail = new SiteServicePredetermineDetail();
        String detailId = IdUtil.uuid();
        detail.setDetailId(detailId);
        detail.setServiceId(qto.getServiceId());
        detail.setPredetermineDate(dbPredetermine.getPredetermineDate());
        detail.setPredetermineTime(dbPredetermine.getPredetermineTime());
        detail.setUserId(userId);
        predetermineDetailMapper.insert(detail);
        predetermineRecordMapper.plusPredetermineCount(detail.getPredetermineId());

        //创建订单号
        String code = CodeUtil.verifyCode(6);
        String today = DateUtil.format(new Date(), "yyyyMMdd");
        String motNo = "MOT".concat(today).concat(code);

        MotOrder order = new MotOrder();
        order.setMotNo(motNo);
        order.setUserId(userId);
        order.setSiteId(qto.getSiteId());
        order.setServiceId(qto.getServiceId());
        order.setCommission(qto.getCommission());
        order.setMotType(qto.getMotType());
        order.setTotalMoney(totalMoney);
        order.setActualPay(totalPay);
        order.setArrivalTime(qto.getArrivalTime());
        order.setPickUpTime(qto.getPickUpTime());
        order.setCarId(qto.getCarId());
        order.setContactPhone(qto.getContactPhone());
        order.setCouponRecordId(qto.getCouponRecordId());
        order.setPickUpAdderss(qto.getPickUpAdderss());
        order.setPickUpFee(pickUpFee);
        order.setDiscountMoney(discountMoney);
        order.setPredetermineDetailId(detailId);
        order.setStatus(PayStatus.PAYING.value());
        //如果存在优惠券，修改为已使用
        if (StringUtils.isNotEmpty(qto.getCouponRecordId())){
            UserCouponRecord record = couponRecordMapper.getByCouponRecordId(qto.getCouponRecordId());
            if (record.getIsForever()!=1) {
                couponRecordMapper.updateStatus(qto.getCouponRecordId(), 1);
            }
        }
//        WxPayUnifiedOrderV3Request v3Request = new WxPayUnifiedOrderV3Request();
//        WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount();
//        amount.setTotal(BaseWxPayRequest.yuanToFen(order.getActualPay().toString()));
//        amount.setCurrency("CNY");
//        v3Request.setAmount(amount);
//        v3Request.setOutTradeNo(motNo);
//        v3Request.setDescription("测试商品");
//        WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
//        payer.setOpenid(userId);
//        v3Request.setPayer(payer);
//        v3Request.setNotifyUrl(motNotifyUrl);
//        // JSAPI返回方法
//        WxPayUnifiedOrderV3Result.JsapiResult v3Result = wxService.createOrderV3(TradeTypeEnum.JSAPI, v3Request);
//
//        return new HttpResult(v3Result);

        if (totalPay==0) {
            order.setPayTime(new Date());
            order.setCloseTime(new Date());
            order.setEndTime(new Date());
            order.setStatus(PayStatus.SUCCESS.value());
            motOrderMapper.insert(order);
            //扣减佣金
            if (null != order.getCommission()) {
                BigDecimal num1 = new BigDecimal(new Double(user.getBalance()).toString());
                BigDecimal num2 = new BigDecimal(new Double(order.getCommission()).toString());
                user.setBalance(num1.subtract(num2).doubleValue());
                userMapper.updateBalance(user);
            }
            WxOrderResult wxOrder = new WxOrderResult();
            wxOrder.setOrderNo(motNo);
            //消息
            UserMessage message = new UserMessage();
            message.setMsgType(1);
            message.setOrderNo(motNo);
            message.setContent("您已下单成功！");
            message.setUserId(userId);
            userMessageMapper.insert(message);
            return new HttpResult(wxOrder);
        }

        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setSignType(WxPayConstants.SignType.MD5);
        orderRequest.setBody("车检订单");
        orderRequest.setOutTradeNo(motNo); //自己生成order_No
        orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
        orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(order.getActualPay().toString()));//直接分
        orderRequest.setOpenid(userId); // 获取微信支付用户的openId
        orderRequest.setSpbillCreateIp(IpUtil.getRealIp(request));
        Date now = new Date();
        Date afterDate = DateUtils.add(now, Calendar.MINUTE, 10);//10分钟后
        orderRequest.setTimeStart(DateUtils.format(now, DateUtils.yyyyMMddHHmmssFormat));
        orderRequest.setTimeExpire(DateUtils.format(afterDate, DateUtils.yyyyMMddHHmmssFormat));
        orderRequest.setNotifyUrl(motNotifyUrl);


        motOrderMapper.insert(order);
        WxPayMpOrderResult wxPayMpOrderResult = wxService.createOrder(orderRequest);
        log.info("微信支付下单返回："+wxPayMpOrderResult.toString());
        WxOrderResult wxOrder = new WxOrderResult();
        wxOrder.setWxPayMpOrderResult(wxPayMpOrderResult);
        wxOrder.setOrderNo(motNo);

        return new HttpResult(wxOrder);

    }



    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @Override
    public String notify(HttpServletRequest request) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult notifyResult = wxService.parseOrderNotifyResult(xmlResult);
            String orderNo = notifyResult.getOutTradeNo();
            String tradeNo = notifyResult.getTransactionId();
            String totalFee = BaseWxPayResult.fenToYuan(notifyResult.getTotalFee());

            MotOrder order = motOrderMapper.getByMotNo(orderNo);
            if(order.getStatus()!=PayStatus.PAYING.value()){
                log.info("车检订单号："+orderNo+"，微信支付重复回调");
                return WxPayNotifyResponse.success("success");
            }
            order.setPayTime(new Date());
            order.setCloseTime(new Date());
            order.setEndTime(new Date());
            if(!"SUCCESS".equals(notifyResult.getResultCode())) {
                order.setStatus(PayStatus.FAIL.value());
//                order.setFailReason(notifyResult.get());
                motOrderMapper.updateOrder(order);
                return WxPayNotifyResponse.success("success");
            }
            if (Double.valueOf(totalFee)<order.getActualPay()){
                order.setStatus(PayStatus.FAIL.value());
                order.setFailReason("订单金额应该与返回金额不一致");
                motOrderMapper.updateOrder(order);
                return WxPayNotifyResponse.fail("订单金额应该与返回金额不一致");
            }
            order.setStatus(PayStatus.SUCCESS.value());
            motOrderMapper.updateOrder(order);
            //扣减佣金
            UserInfo user = userMapper.getByUserId(order.getUserId());
            if (null!=order.getCommission()) {
                BigDecimal num1 = new BigDecimal(new Double(user.getBalance()).toString());
                BigDecimal num2 = new BigDecimal(new Double(order.getCommission()).toString());
                user.setBalance(num1.subtract(num2).doubleValue());
                userMapper.updateBalance(user);
                UserBalanceRecord balanceRecord = new UserBalanceRecord();
                balanceRecord.setBalance(order.getCommission());
                balanceRecord.setUserId(user.getUserId());
                balanceRecord.setRecordName("车检扣减佣金");
                balanceRecord.setRecordType(2);
                balanceRecord.setOrderNo(order.getMotNo());
                balanceRecordMapper.insert(balanceRecord);
            }
            //消息
            UserMessage message = new UserMessage();
            message.setMsgType(1);
            message.setOrderNo(orderNo);
            message.setContent("您已下单成功！");
            message.setUserId(order.getUserId());
            userMessageMapper.insert(message);
            return WxPayNotifyResponse.success("success");
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("产品购买回调失败"+e.getMessage());
        }
    }

    @Override
    public HttpResult cancelMotOrder(HttpServletRequest request, MotOrder order) {

        MotOrder motOrder = motOrderMapper.getByMotNo(order.getMotNo());
        SiteServicePredetermineDetail detail= predetermineDetailMapper.getByDetailId(motOrder.getPredetermineDetailId());
        //取消预约记录
        String userId = tokenUtil.getUserId(request);
        motOrder.setUserId(userId);
        detail.setStatus(-1);
        predetermineDetailMapper.updatePredetermineStatus(detail);
        predetermineRecordMapper.subtractPredetermineCount(detail.getPredetermineId());
        if (StringUtils.isNotEmpty(motOrder.getPickUpAdderss())&&null!=motOrder.getPickUpTime()){
            motOrder.setStatus(MotOrderStatus.WAIT_REFUND.value());
            motOrderMapper.updateOrder(motOrder);
            //消息
            UserMessage message = new UserMessage();
            message.setMsgType(1);
            message.setOrderNo(order.getMotNo());
            message.setContent("您的订单已发起取消申请，请等待平台人员核实接车情况并退款！");
            message.setUserId(motOrder.getUserId());
            userMessageMapper.insert(message);
        }else{
            //没有接车服务全额退款，直接取消订单
            WxPayRefundRequest refundRequest = new WxPayRefundRequest();
            refundRequest.setOutTradeNo(motOrder.getMotNo());
            refundRequest.setOutRefundNo(motOrder.getMotNo());
            //订单总金额
            Integer totalFee = BaseWxPayRequest.yuanToFen(motOrder.getActualPay().toString());
            //退款金额
            Integer refundFee = BaseWxPayRequest.yuanToFen(motOrder.getActualPay().toString());

            refundRequest.setTotalFee(totalFee);
            refundRequest.setRefundFee(refundFee);
            refundRequest.setNotifyUrl(backMotNotifyUrl);
            try {
                WxPayRefundResult refund = wxService.refund(refundRequest);
                log.info("车检订单退款返回：{}",refund);
            }catch (Exception e){
                e.printStackTrace();
            }
            motOrder.setStatus(MotOrderStatus.CANCEL.value());
            motOrderMapper.updateOrder(motOrder);
        }
        return HttpResult.OK;
    }


    @Override
    public String backMotNotify(HttpServletRequest request) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayRefundNotifyResult notifyResult = wxService.parseRefundNotifyResult(xmlResult);
            //判断你返回状态信息是否正确
            if ("SUCCESS".equals(notifyResult.getReturnCode())) {
                WxPayRefundNotifyResult.ReqInfo reqInfo = notifyResult.getReqInfo();
                //判断退款状态
                if ("SUCCESS".equals(reqInfo.getRefundStatus())) {
                    //内部订单号
                    String motNo = reqInfo.getOutRefundNo();
                    MotOrder motOrder = motOrderMapper.getByMotNo(motNo);
                    if (motOrder.getStatus()==MotOrderStatus.CANCEL.value()){
                        return WxPayNotifyResponse.success("success");
                    }
                    motOrder.setStatus(MotOrderStatus.CANCEL.value());
                    motOrderMapper.updateOrder(motOrder);
                    //如果存在优惠券
                    if (StringUtils.isNotEmpty(motOrder.getCouponRecordId())){
                        couponRecordMapper.updateStatus(motOrder.getCouponRecordId(), 0);
                    }
                    //如果存在佣金
                    if (null!=motOrder.getCommission()) {
                        UserInfo user = userMapper.getByUserId(motOrder.getUserId());
                        BigDecimal num1 = new BigDecimal(new Double(user.getBalance()).toString());
                        BigDecimal num2 = new BigDecimal(new Double(motOrder.getCommission()).toString());
                        user.setBalance(num1.add(num2).doubleValue());
                        userMapper.updateBalance(user);
                        UserBalanceRecord balanceRecord = new UserBalanceRecord();
                        balanceRecord.setBalance(motOrder.getCommission());
                        balanceRecord.setUserId(user.getUserId());
                        balanceRecord.setRecordName("车检退还佣金");
                        balanceRecord.setRecordType(1);
                        balanceRecord.setOrderNo(motNo);
                        balanceRecordMapper.insert(balanceRecord);
                    }
                    //消息
                    UserMessage message = new UserMessage();
                    message.setMsgType(1);
                    message.setOrderNo(motOrder.getMotNo());
                    message.setContent("您的订单已取消！");
                    message.setUserId(motOrder.getUserId());
                    userMessageMapper.insert(message);
                    return WxPayNotifyResponse.success("success");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return WxPayNotifyResponse.fail("回调异常");
    }

    public HttpResult reservation(HttpServletRequest request, ComposeCommitDto qto) {
        String userId = tokenUtil.getUserId(request);
        //创建订单号
        String code = CodeUtil.verifyCode(6);
        String today = DateUtil.format(new Date(), "yyyyMMdd");
        String reservationNo = "RE".concat(today).concat(code);

        MotReservation order = new MotReservation();
        order.setReservationNo(reservationNo);
        order.setUserId(userId);
        order.setSiteId(qto.getSiteId());
        order.setServiceId(qto.getServiceId());
        order.setArrivalTime(qto.getArrivalTime());
        order.setCarId(qto.getCarId());
        order.setContactPhone(qto.getContactPhone());
        order.setProblemMsg(qto.getProblemMsg());

        reservationMapper.insert(order);


        //消息
        UserMessage message = new UserMessage();
        message.setMsgType(2);
        message.setOrderNo(reservationNo);
        message.setContent("您已成功预约汽车保养/维修服务！");
        message.setUserId(userId);
        userMessageMapper.insert(message);
        return HttpResult.OK;

    }

    @Override
    public HttpResult reservationDetail(HttpServletRequest request, MotReservation reservation) {
        MotReservation dbreservation = reservationMapper.getByReservationNo(reservation.getReservationNo());
        dbreservation.setCar(userCarMapper.getByCarId(dbreservation.getCarId()));
        dbreservation.setSiteInfo(siteInfoMapper.getBySiteId(dbreservation.getSiteId()));
        return new HttpResult(dbreservation);
    }

    @Override
    public HttpResult cancelReservation(HttpServletRequest request, MotReservation reservation) {
        reservation.setStatus(-1);
        reservationMapper.updateStatus(reservation);
        return HttpResult.OK;
    }


}
